package base.utils

import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * @author njmsir
 * Created by njmsir on 2017/10/10.
 */
class Md5Util {
    companion object {
        private val hextable = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')

        fun byteArrayToHex(array: ByteArray): String {
            var s = ""
            (0 until array.size).forEach { i ->
                var di = (array[i] + 256) and 0xFF
                s = s + hextable[(di shr 4) and 0xF] + hextable[di and 0xF]
            }
            return s
        }

        fun digest(s: String, algorithm: String): String {
            var message: MessageDigest
            try {
                message = MessageDigest.getInstance(algorithm)
            } catch (e: NoSuchAlgorithmException) {
                e.printStackTrace()
                return s
            }

            try {
                message.update(s.toByteArray(charset("UTF-8")))
            } catch (e: UnsupportedEncodingException) {
                e.printStackTrace()
                message.update(s.toByteArray(charset("UTF-8")))
            }
            return byteArrayToHex(message.digest())
        }

        fun md5(s: String): String {
            return digest(s, "MD5")
        }
    }
}